#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : FileServiceApi.py
@Time : 2025/2/20 17:52
@Author: Wangwc
@Describe:  ……
"""

from utils.requests_tools import HttpRequest, check_response, retry_func
from utils.login import Login
from commons.logger import log
from utils.ssh_tools import create_ssh_client_as_root, create_raid_with_shell

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = 'cloud.ini'

assert_message = {'code': 200, 'msg': 'success'}
login = Login(config_name=config_name)
token = login.login()


class FileServiceApi:

    def __init__(self, u_token, configname=config_name):
        self.http = HttpRequest(configname, u_token=u_token)

    @check_response(ext="data", check=assert_message)
    def get_smb_config(self):
        """
        获取smb配置信息
        :return: smb配置信息
        """
        log.debug("开始执行获取smb配置信息操作")
        path = "/ugreen/v1/file/smb/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取smb配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def stop_smb_service(self):
        """
        关闭smb服务
        :return:
        """
        log.debug("开始执行关闭smb服务操作")
        path = "/ugreen/v1/file/smb/stop"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭smb服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def start_smb_service(self, nas_name):
        """
        开启smb服务
        :param nas_name 主机名称
        :return:
        """
        log.debug("开始执行开启smb服务操作")
        path = "/ugreen/v1/file/smb/start"
        data = {"status": True, "work_group": "WORKGROUP", "is_joined_domain": False,
                "hide_share_dir_for_no_permission": True, "enable_log": True, "log_events": [1], "wins_server": "",
                "smb_protocols": [2], "max_protocol": 0, "min_protocol": 0, "encrypt_mode": 0, "server_sign_mode": 1,
                "enable_op_locks": True, "enable_smb2_leases": True, "enable_smb_durable_handles": False,
                "enable_vfs_for_mac_special_char": True, "enable_afp_locking": False,
                "enable_local_master_browser": False, "enable_dir_sort_vfs": False, "enable_veto_files": False,
                "veto_files": "", "enable_delete_veto_files": False, "enable_follow_symlinks": True,
                "enable_wide_links": False, "disable_many_conn_same_ip": False, "enable_debug_log": False,
                "enable_umask": False, "disable_strict_allocate": False, "enable_ntlmv1": False,
                "enable_async_read": False, "enable_monitor_child_dir_change": True, "enable_strict_sync": False,
                "enable_smb3_multi_channel": False, "enable_wildcard_search_cache": False,
                "nas_name": nas_name}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启smb服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def del_smb_cache(self):
        """
        删除smb缓存
        :return:
        """
        log.debug("开始执行删除smb缓存操作")
        path = "/ugreen/v1/file/smb/cache"
        try:
            response = self.http.delete(path)
            return response
        except Exception as e:
            log.error(f"在删除smb缓存过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def start_ftp_service(self, status=True, enable_ftp=True, enable_ftps=True, port=21, enable_log=False,
                          enable_debug=False, enable_umask=False, timeout=300, enable_pasv_port=False, pasv_min_port=0,
                          pasv_max_port=0, enable_pasv_ext_ip=False, pasv_ext_ip="", enable_fxp=False,
                          enable_ascii=False, enable_utf8=True, enable_local_time=False, enable_max_per_ip=False,
                          max_per_ip=2, enable_rate=False, max_upload_rate=0,max_download_rate=0):
        """
        开启ftp服务
        :param status:服务状态，当enable_ftp与enable_ftps都为Fasle时为False，否则为True
        :param enable_ftp:是否开启ftp服务，默认为True
        :param enable_ftps:是否开启ftps服务，默认为True
        :param port:ftp服务端口，默认为21
        :param enable_log:是否开启ftp日志，默认为False
        :param enable_debug:是否开启ftp调试日志，默认为False
        :param enable_umask:是否开启ftp权限掩码，默认为False
        :param timeout:ftp超时时间，默认为300
        :param enable_pasv_port:是否开启ftp被动端口，默认为False
        :param pasv_min_port:ftp被动端口最小值，默认为0
        :param pasv_max_port:ftp被动端口最大值，默认为0
        :param enable_pasv_ext_ip:是否开启ftp被动外部ip，默认为False
        :param pasv_ext_ip:ftp被动外部ip，默认为空
        :param enable_fxp:是否开启ftp fxp，默认为False
        :param enable_ascii:是否开启ftp ascii，默认为False
        :param enable_utf8:是否开启ftp utf8，默认为True
        :param enable_local_time:是否开启ftp本地时间，默认为False
        :param enable_max_per_ip:是否开启ftp最大连接数，默认为False
        :param max_per_ip:ftp最大连接数，默认为2
        :param enable_rate:是否开启ftp速率限制，默认为False
        :param max_upload_rate:ftp最大上传速率，默认为0
        :param max_download_rate:ftp最大下载速率，默认为0
        :return:
        """
        log.debug("开始执行开启ftp服务操作")
        path = "/ugreen/v1/file/ftp/start"
        data = {"status": status, "enable_ftp": enable_ftp, "enable_ftps": enable_ftps, "port": port, "enable_log": enable_log,
                "enable_debug": enable_debug, "enable_umask": enable_umask, "timeout": timeout, "enable_pasv_port": enable_pasv_port,
                "pasv_min_port": pasv_min_port, "pasv_max_port": pasv_max_port, "enable_pasv_ext_ip": enable_pasv_ext_ip, "pasv_ext_ip": pasv_ext_ip,
                "enable_fxp": enable_fxp, "enable_ascii": enable_ascii, "enable_utf8": enable_utf8, "enable_local_time": enable_local_time,
                "enable_max_per_ip": enable_max_per_ip, "max_per_ip": max_per_ip, "enable_rate": enable_rate, "max_upload_rate": max_upload_rate,
                "max_download_rate": max_download_rate}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启ftp服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def stop_ftp_service(self):
        """
        关闭ftp服务
        :return:
        """
        log.debug("开始执行关闭ftp服务操作")
        path = "/ugreen/v1/file/ftp/stop"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭ftp服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_ftp_config(self):
        """
        获取ftp配置
        :return:
        """
        log.debug("开始执行获取ftp配置操作")
        path = "/ugreen/v1/file/ftp/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取ftp配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def check_port(self, module, port,name=None):
        """
        检查端口是否被占用
        :return:
        """
        log.debug("开始执行检查端口是否被占用操作")
        path = "/ugreen/v1/file/checkport"
        params = {"module": module, "port": port}
        if name is not None:
            params["name"] = name
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在检查端口是否被占用过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def start_nfs_service(self, enableNfsServer=True, enableAdvanced=True, maximumNFSProtocol="NFSv3",
                          applyDefaultUNIXPerm=True,
                          customerPort=False, nFSvDomain="",
                          logs=True, statport=None, nlockmgrport=None):
        """
        开启nfs服务
        :param enableNfsServer: 是否开启nfs服务
        :param maximumNFSProtocol: nfs协议版本
        :param applyDefaultUNIXPerm: 是否应用默认UNIX权限
        :param customerPort: 是否使用自定义端口
        :param statdPort: statd端口
        :param nlockMgrPort: nlockmgr端口
        :return:
        """
        log.debug("开始执行开启nfs服务操作")
        path = "/ugreen/v1/file/nfs/start"
        data = {"enableNfsServer": enableNfsServer, "enableAdvanced": enableAdvanced,
                "maximumNFSProtocol": maximumNFSProtocol, "applyDefaultUNIXPerm": applyDefaultUNIXPerm,
                "customerPort": customerPort, "nFSvDomain": nFSvDomain, "defaultReadPacketSize": 8,
                "defaultWritePacketSize": 8, "logs": logs}
        if statport is not None:
            data["statdPort"] = statport
        if nlockmgrport is not None:
            data["nlockmgrPort"] = nlockmgrport
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启nfs服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def stop_nfs_service(self):
        """
        关闭nfs服务
        :return:
        """
        log.debug("开始执行关闭nfs服务操作")
        path = "/ugreen/v1/file/nfs/stop"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭nfs服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_nfs_config(self):
        """
        获取nfs配置
        :return:
        """
        log.debug("开始执行获取nfs配置操作")
        path = "/ugreen/v1/file/nfs/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取nfs配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_user_list(self):
        """
        获取用户列表
        :return:
        """
        log.debug("开始执行获取用户列表操作")
        path = "/ugreen/v1/filemgr/userList"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_rsync_config(self):
        """
        获取rsync配置信息
        :return:
        """
        log.debug("开始执行获取rsync配置信息操作")
        path = "/ugreen/v1/file/rsync/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取rsync配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def start_rsync_service(self, account, password='', status=True, port=8731):
        """
        开启rsync服务
        :param account:用户名
        :param password:密码
        :param status:状态
        :param port:端口
        :return:
        """
        log.debug("开始执行开启rsync服务操作")
        path = "/ugreen/v1/file/rsync/start"
        data = {"status": status, "account": account, "password": password, "port": port}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启rsync服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def stop_rsync_service(self):
        """
        关闭rsync服务
        :return:
        """
        log.debug("开始执行关闭rsync服务操作")
        path = "/ugreen/v1/file/rsync/stop"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭rsync服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_webdav_config(self):
        """
        获取webdav配置信息
        :return:
        """
        log.debug("开始执行获取webdav配置信息操作")
        path = "/ugreen/v1/file/webdav/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取webdav配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def start_webdav_service(self,enable_http=True, enable_https=True, http_port=5005, https_port=5006,
                             enable_anonymous=False, enable_webdav_log=True, disable_path_len_constraint=True):
        """
        开启rsync服务
        :param status:状态
        :param enable_http:是否启用http
        :param enable_https:是否启用https
        :param http_port:http端口
        :param https_port:https端口
        :param enable_anonymous:是否启用匿名访问
        :param enable_webdav_log:是否启用webdav日志
        :param disable_path_len_constraint:是否禁用路径长度限制
        :return:
        """
        log.debug("开始执行开启webdav服务操作")
        path = "/ugreen/v1/file/webdav/start"
        status = False if enable_http == False and enable_https == False else True
        data = {"status": status, "enable_http": enable_http, "enable_https": enable_https, "http_port": http_port,
                "https_port": https_port,
                "enable_anonymous": enable_anonymous, "enable_webdav_log": enable_webdav_log,
                "disable_path_len_constraint": disable_path_len_constraint}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启webdav服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def stop_webdav_service(self):
        """
        关闭webdav服务
        :return:
        """
        log.debug("开始执行关闭webdav服务操作")
        path = "/ugreen/v1/file/webdav/stop"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭webdav服务过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_advanced_config(self):
        """
        获取advanced配置信息
        :return:
        """
        log.debug("开始执行获取advanced配置信息操作")
        path = "/ugreen/v1/file/advanced/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取advanced配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def start_advanced_service(self, shareFolders, enableWsdd2Service=True, enableBonjourService=True,
                             enableTimeMachine=True, enableUPnPService=True):
        """
        开启advanced中的服务
        :param shareFolders:共享文件夹 列表嵌套字典，示例：[{"fileId": 20, "fileName": "raid0", "select": False}]
        :param enableWsdd2Service:是否启用wsdd2服务
        :param enableBonjourService:是否启用bonjour服务
        :param enableTimeMachine:是否启用time machine服务
        :param enableUPnPService:是否启用upnp服务
        :return:
        """
        log.debug("开始执行开启webdav服务操作")
        path = "/ugreen/v1/file/advanced/start"
        data = {"enableWsdd2Service": enableWsdd2Service, "enableBonjourService": enableBonjourService,
                "enableTimeMachine": enableTimeMachine,
                "enableUPnPService": enableUPnPService, "shareFolders": shareFolders, }
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启advanced服务过程中出现异常，异常信息: {e}")
            raise


if __name__ == "__main__":
    pass
